package com.yudaob2b.elong.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yudaob2b.business.constant.AliyunConstant;
import com.yudaob2b.business.entity.po.*;
import com.yudaob2b.business.service.*;
import com.yudaob2b.business.utils.aliyun.mq.CloudMQUtil;
import com.yudaob2b.common.utils.DateUtil;
import com.yudaob2b.common.utils.ExceptionUtil;
import com.yudaob2b.common.utils.PageUtil;
import com.yudaob2b.elong.constant.Constant;
import com.yudaob2b.elong.entity.dto.ELaElongHotelInvDTO;
import com.yudaob2b.elong.entity.dto.ELaElongHotelRateDTO;
import com.yudaob2b.elong.entity.vo.HotelDataRpResult;
import com.yudaob2b.elong.entity.vo.HotelRatePlan;
import com.yudaob2b.elong.entity.vo.Inventory;
import com.yudaob2b.elong.entity.vo.Rate;
import com.yudaob2b.elong.entity.vo.hotellist.HotelIndex;
import com.yudaob2b.elong.entity.vo.hotellist.HotelXMLIndex;
import com.yudaob2b.elong.entity.vo.result.*;
import com.yudaob2b.elong.enums.EnumIncrType;
import com.yudaob2b.elong.enums.EnumPaymentType;
import com.yudaob2b.elong.enums.ela.EnumElasticElongIndexName;
import com.yudaob2b.elong.service.HotelInventoryService;
import com.yudaob2b.elong.service.HotelRateService;
import com.yudaob2b.elong.service.HttpStaticService;
import com.yudaob2b.elong.service.RedisPublisherService;
import org.frameworkset.elasticsearch.ElasticSearchHelper;
import org.frameworkset.elasticsearch.client.ClientInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Wrapper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * @Author: Kidd.Tan
 * @Description
 * @Date: Create in 10:52 2018/7/4
 */
@RestController
@RequestMapping("/test")
public class TestController {
    private static Logger testlogger = LoggerFactory.getLogger("testLogger");

    @Resource(name = "sysUserService2")
    private SysUserService sysUserService;

    @Resource(name = "httpStaticService")
    private HttpStaticService httpStaticService;

    @Resource(name = "elongHotelListService")
    private ElongHotelListService elongHotelListService;

    @Resource(name = "elongHotelListTempService")
    private ElongHotelListTempService elongHotelListTempService;

    @Resource(name = "elongHotelDetailService")
    private ElongHotelDetailService elongHotelDetailService;


    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisPublisherService redisPublisherService;

    @Autowired
    private ElongHotelInventoryService elongHotelInventoryService;

    @Autowired
    private HotelRateService hotelRateService;

    @Autowired
    private ElongHotelRateService elongHotelRateService;

    @Autowired
    private HotelInventoryService hotelInventoryService;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor taskExecutor;

    @Resource(name = "dataInvLocalTaskExecutor")
    private ThreadPoolTaskExecutor dataInvLocalTaskExecutor;

    @RequestMapping("/test1")
    public String test1(String hotelId) throws ParseException {
        testElongApi(hotelId);

        /*String testList = "testList";
        redisTemplate.delete(testList);
        int i = 1;
        while (i < 10) {
            redisTemplate.opsForList().leftPush(testList, String.valueOf(i));
            i++;
        }

        List<String> list = new ArrayList<>();
        int t = 0;
        while (t < 8) {
            String str = (String) redisTemplate.opsForList().rightPop(testList);
            list.add(str);
            t++;
        }



        for (String str : list) {
            System.out.println("s: " + str);
        }
        System.out.println(redisTemplate.opsForList().size(testList));*/

        /*HotelDataInventoryResult hotelDataInventoryResult = httpStaticService.getHotelDataInventory("00101013", null, null, DateUtils.parse("2018-7-20", DateUtils.DATE_PATTERN), DateUtils.parse("2018-7-29", DateUtils.DATE_PATTERN), null);
        for (Inventory inventory : hotelDataInventoryResult.getResult().getInventories()) {
            ElongHotelInventoryPO elongHotelInventoryPO = new ElongHotelInventoryPO();
            BeanUtils.copyProperties(inventory, elongHotelInventoryPO);
            elongHotelInventoryPO.setHotelId(inventory.getHotelID());
            elongHotelInventoryPO.setRoomTypeId(inventory.getRoomTypeId());
            elongHotelInventoryService.insert(elongHotelInventoryPO);
        }*/


       /* Map<String, Object> condition = new HashMap<>();
        condition.put("status", "0");
        PageUtil.setPage(1, 3, condition);
        List<String> list = elongHotelListService.queryHotelIdListPage(condition);
        for (String str : list) {
            System.out.println(str);
        }*/


        /*EntityWrapper<ElongHotelInventoryPO> ew = new EntityWrapper<>();
        ew.where("hotel_id={0}","1")
                .and("room_type_id={0}","2")
                .and("hotel_code='3'")
                .and("date='2018-07-16'");
        System.out.println(ew.getSqlSegment());
        int count = elongHotelInventoryService.selectCount(ew);
        System.out.println(count);*/

        /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<ElongHotelInventoryPO> list = new ArrayList<>();
        ElongHotelInventoryPO po = new ElongHotelInventoryPO();
        po.setHotelId("1");
        po.setRoomTypeId("2");
        po.setHotelCode("3");
        po.setDate(sdf.parse("2018-07-16"));
        po.setAmount(1111);
        list.add(po);
        ElongHotelInventoryPO po2 = new ElongHotelInventoryPO();
        po2.setHotelId("1");
        po2.setRoomTypeId("2");
        po2.setHotelCode("4");
        po2.setDate(sdf.parse("2018-07-16"));
        po2.setAmount(23232);
        list.add(po2);
        elongHotelInventoryService.updateBatch(list);*/

       /* EntityWrapper<ElongHotelRatePO> ew = new EntityWrapper();
        ew.where("hotel_id={0}","00101006");
        List<ElongHotelRatePO> list = elongHotelRateService.selectList(ew);
System.out.println(JSONObject.toJSONString(list));*/

       /* StringBuilder indexBuilder = new StringBuilder();
        indexBuilder.append("00101006").append("_")
                .append("0001").append("_")
                .append("92365485").append("_")
                .append("2018-07-17");
        //int count = (int) redisTemplate.opsForValue().get(indexBuilder.toString());
        System.out.println(redisTemplate.hasKey(indexBuilder.toString()));*/

        long start = System.currentTimeMillis();


        /*EntityWrapper ew = new EntityWrapper<>();
        ew.where("hotel_id={0}", "00201056")
                .and("room_type_id={0}", "0160")
                .and("hotel_code={0}", "91556621")
                .and("date={0}", "2018-08-05");
        List<ElongHotelInventoryPO> list = elongHotelInventoryService.selectList(ew);
        System.out.println(list.size());
        System.out.println(System.currentTimeMillis() - start);
*/


        /*Producer producer = CloudMQUtil.getProducer(AliyunConstant.PID_ELONGHOTEL);
        Message msg = new Message(AliyunConstant.TOPIC_INCR_INV_NAME, "tag_003", "key_003", "这是消息".getBytes());
        producer.send(msg);*/

        /*EntityWrapper ew = new EntityWrapper<>();
        int a = elongHotelInventoryService.selectCount(ew);
        System.out.println(a);
*/

        System.out.println(System.currentTimeMillis() - start);
        //batchSaveEla();

        return "ok";
    }

    private void batchSaveEla() {
        long start = System.currentTimeMillis();
        List<ELaElongHotelRateDTO> list = new ArrayList<>();


        /*for (int i = 50000; i <= 10000000; i++) {
            ELaElongHotelRatePO po1 = new ELaElongHotelRatePO();
            po1.setStatus(0);
            po1.setRatePlanId("1");
            po1.setRatePlanId("2");
            po1.setStartDate(new Date());
            po1.setEndDate(new Date());
            po1.setHotelCode("3");
            po1.setMember(BigDecimal.valueOf(12));
            po1.setPriceId(5l);
            po1.setCurrencyCode("RMB");
            po1.setId(String.valueOf(i));
            po1.setHotelId(String.valueOf(i));
            list.add(po1);
            if (list.size() == 500) {
                ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
                String result = clientUtil.addDocuments("kidtest",//索引表
                        "test",//索引类型
                        list);
                list.clear();
                break;
            }
        }*/

        List<ELaElongHotelInvDTO> hotelRatePlanList = new ArrayList<>();
        ELaElongHotelInvDTO dto = new ELaElongHotelInvDTO();
        dto.setId("1");
        dto.setStatus(1);
        hotelRatePlanList.add(dto);
        ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
        String result = clientUtil.addDocuments(EnumElasticElongIndexName.INVENTORY.getIndexName(),//索引表
                EnumElasticElongIndexName.INVENTORY.getType(),//索引类型
                hotelRatePlanList);
        System.out.println("result: " + result);

        /*ClientInterface clientUtil = ElasticSearchHelper.getRestClientUtil();
        String result = clientUtil.addDocuments("kidtest",//索引表
                "test",//索引类型
                list);
        System.out.println(result);*/
        System.out.println("ok:" + (System.currentTimeMillis() - start));
    }

    private void testElongApi(String hotelId) {
        // 查询开始时间，当天时间
        Date ratestartDate = new Date();
        // 查询结束时间，90天后的时间
        Date rateEndDate = DateUtil.rollDay(ratestartDate, Constant.INCR_DAYS);

        //HotelIncrRateResult resultVO = httpStaticService.gethotelIncrRate(18174610366l);
        //HotelIncrInvResult resultVO = httpStaticService.gethotelIncrInv(72928073572l);
        //HotelIncrStateResult resultVO = httpStaticService.gethotelIncrState(2811285087l);
        //HotelIncrIdResult resultVO = httpStaticService.getHotelIncrId(new Date(), EnumIncrType.Rate);
        HotelDataRateResult resultVO = httpStaticService.getHotelDataRate(hotelId, null, EnumPaymentType.Prepay, DateUtil.parse("2018-10-20", DateUtil.PATTERN_CLASSICAL_SIMPLE), DateUtil.parse("2018-10-25", DateUtil.PATTERN_CLASSICAL_SIMPLE));

        //HotelDataRpResult resultVO = httpStaticService.gethotelDataRp("00101012", EnumPaymentType.Prepay,null);
        //HotelDataInventoryResult resultVO = httpStaticService.getHotelDataInventory(hotelId, null, null, DateUtil.parse("2018-07-22", DateUtil.PATTERN_CLASSICAL_SIMPLE), DateUtil.parse("2018-10-22", DateUtil.PATTERN_CLASSICAL_SIMPLE), null);

        /*long start = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtil.PATTERN_CLASSICAL_SIMPLE);
        for (Inventory inv : resultVO.getResult().getInventories()) {
            EntityWrapper ew = new EntityWrapper<>();
            ew.where("hotel_id={0}", inv.getHotelID())
                    .and("room_type_id={0}", inv.getRoomTypeId())
                    .and("hotel_code={0}", inv.getHotelCode())
                    .and("date={0}", DateUtil.SDF_PATTERN_CLASSICAL_SIMPLE.format(inv.getDate()));
            elongHotelInventoryService.selectCount(ew);

        }
        System.out.println("ss:" + resultVO.getResult().getInventories().size() + "-----" + (System.currentTimeMillis() - start));*/


        System.out.println(JSONObject.toJSONString(resultVO));
    }

    private void gethotelDataRp(String hotelId, EnumPaymentType paymentType, String options) {
        httpStaticService.gethotelDataRp(hotelId, paymentType, options);
    }

    @RequestMapping("/test")
    public String test() throws ParseException {
        testlogger.info("okkk");
        try {
            /*if (redisLockService.lock("aa")) {

            }*/
            String s = null;
            s.indexOf("1");
        } catch (Exception e) {
            testlogger.info("error:{}" + ExceptionUtil.getTrace(e));
            e.printStackTrace();
        }
        /*long start = System.currentTimeMillis();

        int limit = 100;
        List<ElongHotelDetailPO> elongHotelDetailPOList = new ArrayList<>();
        List<ElongHotelListTempPO> hotelList = elongHotelListTempService.selectByMap(new HashMap<>());
        int listSize = hotelList.size();

        for (int i = 0; i < hotelList.size(); i += limit) {
            StringBuilder ids = new StringBuilder();
            long s = System.currentTimeMillis();
            if (i + limit > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
                limit = listSize - i;
            }
            List<ElongHotelListTempPO> newList = hotelList.subList(i, i + limit);

            List<FutureTask<ElongHotelDetailPO>> futureTaskList = new ArrayList<>(limit);
            for (ElongHotelListTempPO po : newList) {
                QueryHotelDetailTask task = new QueryHotelDetailTask(String.valueOf(po.getHotelId()), httpStaticService);
                FutureTask<ElongHotelDetailPO> futureTask = new FutureTask<>(task);
                futureTaskList.add(futureTask);
                threadPoolTaskExecutor.execute(futureTask);
                ids.append(po.getHotelId()).append(",");
            }

            //System.out.println(ids);
            for (FutureTask<ElongHotelDetailPO> futureTask : futureTaskList) {
                try {
                    ElongHotelDetailPO elongHotelDetailPO = futureTask.get(30000, TimeUnit.MILLISECONDS);
                    if (elongHotelDetailPO != null) {
                        elongHotelDetailPOList.add(elongHotelDetailPO);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(elongHotelDetailPOList.size());
        System.out.println("time is ：" + (System.currentTimeMillis() - start));
*/
        return "ok";
    }

    /**
     * 执行多线程去中软那边请求数据
     *
     * @param futureTaskList 子线程列表
     */
    private void runTask(List<FutureTask<List<ElongHotelDetailPO>>> futureTaskList) {
        for (FutureTask<List<ElongHotelDetailPO>> futureTask : futureTaskList) {
            try {
                futureTask.get(15000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }
    }
}
